package com.atguigu.flink.chapter11;

import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.ZoneOffset;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/8/20 10:54
 */
public class Flink21_SQL_Over_Window {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        
        env.setParallelism(1);
        
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        tenv.getConfig().setLocalTimeZone(ZoneOffset.ofHours(0)); // 设置事件时间使用的时区
        // 1. 需要有一个时间戳类型的字段(作为事件属性)  2. 需要定义水印
        // bigint->timestamp   | bigint ->(from_unixtime) "datatime 的字符" ->(to_timestamp) timestamp
        tenv.executeSql("create table sensor(" +
                            "   id string, " +
                            "   ts bigint, " +
                            "   vc int, " +
                            "   et as to_timestamp(from_unixtime(ts/1000)), " +
                            "   watermark for et as et - interval '3' second " +
                            ")with(" +
                            "   'connector' = 'filesystem', " +
                            "   'path' = 'input/sensor.txt'," +
                            "   'format' = 'csv' " +
                            ")");
        
        /*tenv.sqlQuery("select" +
                          " id, " +
                          " et," +
                          " vc, " +
//                          " sum(vc) over(partition by id order by et rows between unbounded preceding and current row) sum_vc " +
//                          " sum(vc) over(partition by id order by et rows between 1 preceding and current row) sum_vc " +
//                          " sum(vc) over(partition by id order by et range between unbounded preceding and current row) sum_vc " +
                          " sum(vc) over(partition by id order by et range between interval '1' second  preceding and current row) sum_vc " +
                          "from sensor ")
            .execute().print();*/
        
        tenv.sqlQuery("select" +
                          " id, " +
                          " et," +
                          " vc, " +
                          " sum(vc) over w sum_vc, " +
                          " max(vc) over w max_vc, " +
                          " min(vc) over w min_vc " +
                          "from sensor " +
                          "window w as (partition by id order by et rows between unbounded preceding and current row)")
            .execute().print();
        
    }
}
